package com.qqin.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qqin.mapper.*;
import com.qqin.pojo.Check;
import com.qqin.pojo.Goods;
import com.qqin.pojo.PageBean;
import com.qqin.service.GoodsService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class GoodsServiceImpl implements GoodsService {
    private AddressMapper addressMapper;
    private CheckMapper checkMapper;
    private GoodsMapper goodsMapper;
    private CommentMapper commentMapper;
    private ItemMapper itemMapper;
    private OrderMapper orderMapper;
    private UsersMapper usersMapper;
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;

    public GoodsServiceImpl() {
        try {
            // 加载数据库配置文件
            Properties properties = new Properties();
            InputStream dbStream = Resources.getResourceAsStream("db.properties");
            properties.load(dbStream);

            // 加载MyBatis配置文件
            String resource = "mybatis-config.xml";
            InputStream mybatisStream = Resources.getResourceAsStream(resource);

            // 创建SqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(mybatisStream, properties);

            // 获取SqlSession
            sqlSession = sqlSessionFactory.openSession();

            // 获取Mapper实例
            checkMapper = sqlSession.getMapper(CheckMapper.class);
            goodsMapper= sqlSession.getMapper(GoodsMapper.class);
            commentMapper= sqlSession.getMapper(CommentMapper.class);
            itemMapper= sqlSession.getMapper(ItemMapper.class);
            orderMapper= sqlSession.getMapper(OrderMapper.class);
            usersMapper= sqlSession.getMapper(UsersMapper.class);
            addressMapper= sqlSession.getMapper(AddressMapper.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public PageBean page(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);

        List<Goods> goods = goodsMapper.selectAll();
        Page<Goods> p = (Page<Goods>)goods;

        return new PageBean(p.getTotal(), p.getResult());
    }

    @Override
    public Goods selectById(Integer goodsId) {
        return goodsMapper.selectById(goodsId);
    }

    @Override
    public List<Goods> selectByListed() {
        return goodsMapper.selectByListed();
    }

    @Override
    public List<Goods> selectByCondition(String goodsName) {

        //验证输入参数
        if (goodsName == null || goodsName.trim().isEmpty()) {
            // 如果 goodsName 为空，可以选择返回空列表或抛出异常
            System.out.println("商品名称为空，返回空列表");
            return Collections.emptyList();
            //不会报空指针异常，如果直接返回Null，没有进行非空判断就会报空指针异常；
        }

        //调用 Mapper 方法进行查询
        List<Goods> goodsList;
        try {
            goodsList = goodsMapper.selectByCondition(goodsName);
        } catch (Exception e) {
            // 捕获异常
            System.err.println("查询商品时发生异常: " + e.getMessage());
            throw new RuntimeException("查询商品失败", e);
        }

        //对查询结果进行后处理
        if (goodsList == null || goodsList.isEmpty()) {
            System.out.println("未找到符合条件的商品");
            return Collections.emptyList();
        }

        //对结果进行排序
        goodsList.sort(Comparator.comparing(Goods::getGoodsName)); // 假设 Goods 类有 getGoodsName 方法
        return goodsList;
    }

    @Override
    public List<Goods> getPhoto(Integer photoNum) {
        List<Goods> goods = goodsMapper.selectByListed();

        if (goods.size() < 4) {
            System.out.println("物品数量不足，轮播图暂不可用");
        }

        List<Goods> photos = new ArrayList<>();

        Random random = new Random();

        for (int i = 0; i < photoNum; i++) {
            int r = random.nextInt(goods.size());
            photos.add(goods.get(r));
            goods.remove(r);
        }

        return photos;
    }

    @Override
    public void add(Goods goods, Integer userId) {
        LocalDateTime nowTime = LocalDateTime.now();
        goods.setCreateTime(nowTime);
        goods.setUpdateTime(nowTime);
        goods.setState(0);
        goodsMapper.add(goods);

        List<Goods> gs = goodsMapper.selectByAny(goods);
        Goods g = gs.get(0);

        Check check = new Check();
        check.setCheckUser(userId);
        check.setCheckGoods(g.getGoodsId());
        check.setState(0);
        checkMapper.add(check);
        sqlSession.commit();
    }

    @Override
    public Goods updateById(Goods goods) {
        LocalDateTime nowTime = LocalDateTime.now();
        goods.setUpdateTime(nowTime);

        //调用方法找到要修改的商品
        Goods g = goodsMapper.selectById(goods.getGoodsId());
        if (g.getState() == 2) {
            System.out.println("该商品已售出");
        } else if (g.getState() == 3) {
            System.out.println("该商品已下架");
        }

        //修改商品
        goodsMapper.updateById(goods);
        sqlSession.commit();
        return goods;
    }

    @Override
    public void delisting(Integer goodsId) {        //cjy：下架商品

        //首先调用方法判断这个商品是否存在
        Goods goods = goodsMapper.selectById(goodsId);


        //判断商品的状态是否可以下架
        if (goods.getState() == 0) {
            System.out.println("该商品未上架");
        } else if (goods.getState() == 2) {
            System.out.println("该商品已售出");
        } else if (goods.getState() == 3) {
            System.out.println("该商品已下架");
        }

        //将商品下架
        goodsMapper.delisting(goodsId);
        sqlSession.commit();
    }


}
